package org.xqyy.eval.service.impl;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.xqyy.eval.dao.*;
import org.xqyy.eval.model.TTestPaperDetail;
import org.xqyy.eval.model.TestPaperDetail;
import org.xqyy.eval.service.IEvalService;
import org.xqyy.eval.util.DataFormatUtil;
import tk.mybatis.mapper.entity.Example;

import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * Created by luoxiaoming on 17-3-2.
 */

@Component
@Transactional(readOnly = true)
public class EvalService implements IEvalService {

    @Autowired
    private IInternalEvalMapperDao internalEvalMapperDao;

    @Autowired
    private IQuestionDao questionDao;

    @Autowired
    private IInternalEvalRecordDao internalEvalRecordDao;

    @Autowired
    private IDeptDao deptDao;

    @Autowired
    private  TEvalDetailMapper evalDetailMapper;
    @Autowired
    private  TTestPaperDetailMapper paperDetailMapper;


    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, readOnly = false)
    public void generatorNextMonthData(Map<String, Object> params) {
        String username = (String) params.get("username");

        List<Map<String, Object>> mapperList = internalEvalMapperDao.load(new HashMap());
        String month = DataFormatUtil.defectDateFormat.format(new Date());
        params.put("month", month);
        int count = this.internalEvalRecordDao.findGeneratorRecordCount(params);
        if (count > 0) {
            throw new RuntimeException("本月已经生成完，不能再次生成!");
        }
        if (mapperList != null) {
            //迭代类别
            for (Map<String, Object> map : mapperList) {
                if (map.get("targetGroupCode") == "005") {


                    Map<String, Object> master = new HashMap<>();

                    String targetGroupCode = (String) map.get("targetGroupCode");

                    List<Map<String, Object>> depts = deptDao.load(map);
                    Map<String, Object> temp = new HashMap<>();
                    temp.put("groupCode", targetGroupCode);
                    List<Map<String, Object>> targetDepts = deptDao.load(temp);

                    // 开始迭代所有科室生成评价数据
                    for (Map<String, Object> dept : depts) {
                        if(dept.get("pcode")=="0"){

                            //迭代目标科室
                            for (Map<String, Object> targetDept : targetDepts) {
                                String masterId = UUID.randomUUID().toString();
                                master.put("id", masterId);
                                master.put("deptCode", dept.get("code"));
                                master.put("targetDeptCode", targetDept.get("code"));
                                master.put("generator", username);
                                master.put("month", month);
                                master.put("generatedTime", new Date());
                                master.put("beginTime", params.get("beginTime"));
                                master.put("endTime", params.get("endTime"));
                                master.put("status", 0);
                                List<Map<String, Object>> questions = questionDao.load(map);
                                // 查询到试卷问题列表后进行明细插入
                                if (questions != null) {
                                    internalEvalRecordDao.add(master);
                                    for (Map<String, Object> question : questions) {
                                        Map<String, Object> detail = new HashMap<>();
                                        try {
                                            BeanUtils.copyProperties(detail, question);
                                            detail.put("id", UUID.randomUUID().toString());
                                            detail.put("masterId", masterId);
                                            detail.put("questionId", question.get("id"));
                                            /*internalEvalRecordDao.addDetail(detail);*/ /*Fun_hanxn190402_mark*/
                                            internalEvalRecordDao.addDetail1(detail); /*Fun_hanxn190402_add*/
                                        } catch (IllegalAccessException e) {
                                            e.printStackTrace();
                                        } catch (InvocationTargetException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }



                        }

                    }






                } else {
                    Map<String, Object> master = new HashMap<>();

                    String targetGroupCode = (String) map.get("targetGroupCode");

                    List<Map<String, Object>> depts = deptDao.load(map);
                    Map<String, Object> temp = new HashMap<>();
                    temp.put("groupCode", targetGroupCode);
                    List<Map<String, Object>> targetDepts = deptDao.load(temp);

                    // 开始迭代所有科室生成评价数据
                    for (Map<String, Object> dept : depts) {
                        //迭代目标科室
                        for (Map<String, Object> targetDept : targetDepts) {
                            String masterId = UUID.randomUUID().toString();
                            master.put("id", masterId);
                            master.put("deptCode", dept.get("code"));
                            master.put("targetDeptCode", targetDept.get("code"));
                            master.put("generator", username);
                            master.put("month", month);
                            master.put("beginTime", params.get("beginTime"));
                            master.put("endTime", params.get("endTime"));
                            master.put("generatedTime", new Date());
                            master.put("status", 0);
                            List<Map<String, Object>> questions = questionDao.load(map);
                            // 查询到试卷问题列表后进行明细插入
                            if (questions != null) {
                                internalEvalRecordDao.add(master);
                                for (Map<String, Object> question : questions) {
                                    Map<String, Object> detail = new HashMap<>();
                                    try {
                                        BeanUtils.copyProperties(detail, question);
                                        detail.put("id", UUID.randomUUID().toString());
                                        detail.put("masterId", masterId);
                                        detail.put("questionId", question.get("id"));
                                        /*internalEvalRecordDao.addDetail(detail);*/ /*Fun_hanxn190402_mark*/
                                        internalEvalRecordDao.addDetail1(detail); /*Fun_hanxn190402_add*/
                                    } catch (IllegalAccessException e) {
                                        e.printStackTrace();
                                    } catch (InvocationTargetException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public List<Map<String, Object>> loadEvalMasterData(Map<String, Object> params) {
        List<Map<String, Object>> data = this.internalEvalRecordDao.loadEvalMasterData(params);
        return data;
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, readOnly = false)
    public void submit(Map<String, Object> params) {




    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, readOnly = false)
    public void autoSubmit(Map<String, Object> params) {

    }

    @Override
    public List<Map<String, Object>> loadEvalPageTabs(Map<String, Object> params) {
        return this.internalEvalRecordDao.loadEvalPageTabs(params);
    }

    @Override
    public Map<String, Object> loadEvalPageContent(Map<String, Object> params) {
        Map<String, Object> res = new HashMap<>();
        List<Map<String, Object>> questions = questionDao.load(params);
        Collections.sort(questions, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                return (int) o1.get("id") - (int) o2.get("id");
            }
        });
        res.put("questions", questions);
        List<Map<String, Object>> masters = this.internalEvalRecordDao.loadEvalMasterRecords(params);

        List<Map<String, Object>> details = this.internalEvalRecordDao.loadDetail(params);
        Map<String, List<Map<String, Object>>> detailMap = buildSortMap(details);
        if (masters != null && !masters.isEmpty()) {
            res.put("masters", masters);
            for (Map<String, Object> master : masters) {
                List<Map<String, Object>> subDetails = detailMap.get(master.get("id"));
                if (subDetails != null) {
                    for (Map<String, Object> detail : subDetails) {
                        master.put(detail.get("questionId") + "", detail.get("grade"));
                    }
                }
            }
        }
        return res;
    }


    private Map<String, List<Map<String, Object>>> buildSortMap(List<Map<String, Object>> details) {
        Map<String, List<Map<String, Object>>> map = new HashMap<>();
        if (details != null && details.size() > 0) {
            for (Map<String, Object> detail : details) {
                List<Map<String, Object>> subDetials = map.get(detail.get("masterId"));
                if (subDetials == null) {
                    subDetials = new ArrayList<>();
                    map.put((String) detail.get("masterId"), subDetials);
                }
                subDetials.add(detail);
            }
        }
        if (!map.isEmpty()) {
            for (Map.Entry<String, List<Map<String, Object>>> entry : map.entrySet()) {
                Collections.sort(entry.getValue(), new Comparator<Map<String, Object>>() {
                    @Override
                    public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                        return (int) o1.get("questionId") - (int) o2.get("questionId");
                    }
                });
            }
        }
        return map;
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, readOnly = false)
    public String modifyDetail(Map<String, Object> params) {
        String reString ="1";
        String mark = (String) params.get("mark");
        params.put("status", "1");
        //if(!internalEvalRecordDao.loadEvalMasterRecords(params).isEmpty())   { //fun_hanxn_190325_mark
        if(!internalEvalRecordDao.loadModifyEvalMasterRecords(params).isEmpty())   { //fun_hanxn_190325_mod
            reString="问卷已提交，不能修改";
        }else {

        if (StringUtils.hasLength(mark)) {
            Map<String, Object> map = new HashMap<>();
            map.put("mark", mark);
            map.put("id", params.get("masterId"));
            this.internalEvalRecordDao.modify(map);
        } else {
            this.internalEvalRecordDao.modifyDetail(params);
        }
        }

        return reString;

    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, readOnly = false)
    public String  submitEval(Map<String, Object> params){
        String reString ="1";
        List<Map<String, Object>> data = internalEvalRecordDao.loadDissatisfiedRecords(params);
        List<Map<String, Object>> data_bmy = internalEvalRecordDao.loadDissatisfiedRecords_bmy(params); /*Fun_hanxn190403_add_评分表不能都是满意*/
      if(!internalEvalRecordDao.loadEvalMasterRecords(params).isEmpty())   {
          reString="问卷已提交，不能重复提交";
      }else {
          if(!internalEvalRecordDao.loadDetail(params).isEmpty() ){
              reString="问卷未完成，请完成后提交提交";
          }
          if (data_bmy.size() == 0) {
              reString += "评分表不能全部评分是满意！";
          }
      else  {
          if(data.size()>0){
              for (Map<String, Object> temp : data)
              {
                  reString+= temp.get("deptName")+"，";
              }
              reString+="有不满意评价，需要填写备注";
          }
          else  this.internalEvalRecordDao.submitMaster(params);
      }

      }



     return  reString;
    }

    /**
     * 查询某个科室在一个填报周期内的具体某张调查问卷的填报情况
     *
     * @param yearmonth 填报周期
     * @param dutyId    科室id
     * @param paperId   试卷id
     * @return
     */
    @Override
    public List<HashMap<String, Object>> evalEdList(String yearmonth, String dutyId, Integer paperId) {
        Example example = new Example(TTestPaperDetail.class);
        example.setOrderByClause("question_id");
        example.createCriteria().andEqualTo("paperId",paperId);
        List<TTestPaperDetail> paperDetails =   paperDetailMapper.selectByExample(example);
        List<Integer> list = new ArrayList<Integer>();
        for (TTestPaperDetail paperDetail : paperDetails) {
            list.add(paperDetail.getQuestionId());
        }
        return evalDetailMapper.evalEdList(dutyId,yearmonth,paperId,list);
    }


}
